package DMSXL._2024.BinaryTrees;

import java.util.LinkedList;
import java.util.Queue;

public class connect {
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        if(root == null){
            return root;
        }
        queue.offer(root);
        while (!queue.isEmpty()){
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                Node cur = queue.poll();

                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
                if(i != n - 1){
                    cur.next = queue.peek();
                }else {
                    cur.next = null;
                }
            }
        }
        return root;

    }
}
